<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="150px">
      <!--      <el-row>-->
      <el-form-item label="关联的MCU设备" prop="mcuTenantResourceId">
        <el-select v-model="queryParams.mcuTenantResourceId" placeholder="请选择关联的MCU设备"
                   clearable
                   @keyup.enter.native="handleQuery"
                   style="width:400px">
          <el-option
            v-for="item in mcuTenantResourceListData"
            :key="item.id"
            :label="item.model+'（'+item.name+'）（'+item.remark+'）'"
            :value="item.id">
            <span style="float: left">{{ item.model }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">（{{ item.name }}）-（{{ item.remark }}）</span>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRangeCreateTime" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-card class="box-card" v-for="item in list" :key="item.sensorTenantResourceId" style="background:#fff;padding:30px 30px 0;margin-bottom:32px;">
      <div slot="header" class="clearfix" style="font-size: 20px; font-weight: bold">
        <span>{{item.sensorName}}</span>
      </div>
      <div class="chart" :id="item.sensorTenantResourceId" style="height:350px;width:100%"/>
    </el-card>
  </div>
</template>

<script>
import {getMonitoringDataStatistical} from "@/api/hardware/monitoringData";
import {getMcuTenantResourceList} from "@/api/hardware/mcuTenantResource";
import {getTenantId} from '@/utils/auth'
import echarts from 'echarts'

require('echarts/theme/macarons') // echarts theme
export default {
  name: "MonitoringDataStatistical",
  components: {},
  data() {
    return {
      // 监测数据列表
      list: [],
      dateRangeCreateTime: [],
      // 查询参数
      queryParams: {
        sensorTenantResourceId: null,
      },
      mcuTenantResourceListData: [],
      tenantId: getTenantId(),
      echartsInitObject: new Map(),
      timer: null
    };
  },
  created() {
    this.getList();
    this.queryMcuTenantResourceListData();
  },
  beforeDestroy() {
    clearTimeout(this.timer);
    this.list.forEach(it => {
      this.echartsInitObject.get(it.sensorTenantResourceId).dispose();
    })
  },
  methods: {
    /**  查询租户添加的MCU 列表  */
    queryMcuTenantResourceListData() {
      getMcuTenantResourceList({tenantId: this.tenantId, reverse: true}).then(response => {
        this.mcuTenantResourceListData = response.data;
        if (this.mcuTenantResourceListData && this.mcuTenantResourceListData.length > 0) {
          this.queryParams.mcuTenantResourceId = this.mcuTenantResourceListData[0].id
        }
      });
    },
    /** 查询列表 */
    getList() {
      // 处理查询参数
      let params = {...this.queryParams};
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行查询
      getMonitoringDataStatistical(params).then(response => {
        //清除旧的
        this.list.forEach(it => {
          this.echartsInitObject.get(it.sensorTenantResourceId).dispose();
        })


        this.list = response.data;
        let letThis = this
        this.timer = setTimeout(() => {
          letThis.list.forEach(it => {
            this.echartsInitObject.set(it.sensorTenantResourceId, echarts.init(document.getElementById(it.sensorTenantResourceId)))
            this.setOptions(it)
          })
          //随着屏幕大小调节图表
          window.addEventListener("resize", () => {
            letThis.list.forEach(it => {
              this.echartsInitObject.get(it.sensorTenantResourceId).resize();
            })
          });
        }, 300);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    }, //项次
    setOptions(item) {
      let seriesData = [];
      let legendData = [];
      item.dataAttributes.forEach(it => {
        legendData.push(it.dataAttributeName)
        seriesData.push({
          name: it.dataAttributeName,
          smooth: true,
          type: 'line',
          data: it.dataList,
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        })
      })
      this.echartsInitObject.get(item.sensorTenantResourceId).setOption({
        xAxis: {
          data: item.xaxis,
          type: "category",
          boundaryGap: false, // 不留白
          axisLabel: {
            showMinLabel: true, // 显示最小标签
            showMaxLabel: true, // 显示最大标签
            formatter: function(params) { //处理理字体显示不全的问题
              let newParamsName = "";
              let paramsNameNumber = params.length;
              let provideNumber = 10; //一行显示几个字
              let rowNumber = Math.ceil(paramsNameNumber / provideNumber);
              if (paramsNameNumber > provideNumber) {
                for (let p = 0; p < rowNumber; p++) {
                  let tempStr = "";
                  let start = p * provideNumber;
                  let end = start + provideNumber;
                  if (p == rowNumber - 1) {
                    tempStr = params.substring(start, paramsNameNumber);
                  } else {
                    tempStr = params.substring(start, end) + "\n";
                  }
                  newParamsName += tempStr;
                }
              } else {
                newParamsName = params;
              }
              return newParamsName;
            }
          }
        },
        grid: {
          left: 30,
          right: 50,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          data: legendData
        },
        series: seriesData
      })
    }
  }
};
</script>


<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>

